package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyCommendService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.IStrategyTagService;
import cn.wolfcode.luowowo.cache.key.RedisKey;
import cn.wolfcode.luowowo.cache.service.IStrategyStatsCacheService;
import cn.wolfcode.luowowo.cache.vo.StrategyStats;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQueryObject;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.common.query.StrategyQueryObject;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.service.IStrategySearchService;
import cn.wolfcode.luowowo.search.vo.StatsResult;
import cn.wolfcode.luowowo.website.annotation.LoginUser;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/strategy")
public class StrategyController {
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IStrategyTagService strategyTagService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyCommentService strategyCommentService;
    @Reference
    private IStrategyCommendService strategyCommendService;
    @Reference
    private IStrategyStatsCacheService strategyStatsCacheService;
    @Reference
    private IStrategySearchService strategySearchService;


    @RequestMapping("")
    public String index(Model model){
        //commends 推荐的攻略
        model.addAttribute("commends",strategyCommendService.listTop5());

        //upCds 飙升排行榜
        model.addAttribute("upCds",strategyStatsCacheService.listCommends(RedisKey.STRATEGY_STATS_UP_SORT));
        //hotCds 热门排行榜
        model.addAttribute("hotCds",strategyStatsCacheService.listCommends(RedisKey.STRATEGY_STATS_HOT_SORT));
        //abroads 国外查询条件
        List<StatsResult> abroads = strategySearchService.listCondition(SearchQueryObject.CONDITION_ABROAD);
        abroads.remove(StatsResult.CHINA);
        model.addAttribute("abroads",abroads);
        //unabroads 国内查询条件
        List<StatsResult> unabroads = strategySearchService.listCondition(SearchQueryObject.CONDITION_UNABROAD);
        model.addAttribute("unabroads",unabroads);
        //themes 主题查询条件
        model.addAttribute("themes",strategySearchService.listCondition(SearchQueryObject.CONDITION_THEME));

        //themeCds
        model.addAttribute("themeCds",strategySearchService.listThemeCommendTop10());
        return "strategy/index";


    }

    //http://localhost/strategy/searchPage
    @RequestMapping("searchPage")
    public String searchPage(@ModelAttribute("qo") SearchQueryObject qo,Model model){
        model.addAttribute("page",strategySearchService.query(qo));
        return "strategy/searchPageTpl";
    }

    @RequestMapping("/detail")
    public String getDetail(Long id, Model model,@LoginUser UserInfo user){

        model.addAttribute("detail",strategyDetailService.get(id));
        //表示该文章被访问了,访问量+1
        strategyStatsCacheService.incrNum(id,1,IStrategyStatsCacheService.STRATEGY_STATS_VIEWNUM);
        //查询该文章的热数据
        model.addAttribute("vo",strategyStatsCacheService.getStrategyStats(id));
        //isFavor查询是否访问这片文章的用户,是否点赞过该文章
        if (user!=null) {
            boolean isFavor = strategyStatsCacheService.isFavor(id, user.getId());
            model.addAttribute("isFavor", isFavor);
        }

        //飙升绑定加分
        strategyStatsCacheService.addScore(RedisKey.STRATEGY_STATS_UP_SORT,1,id);
        return "strategy/detail";
    }

    //strategy/list?destId=3261
    @RequestMapping("list")
    public String listStrategy(@ModelAttribute("qo") StrategyQueryObject qo, Model model){
        PageInfo<StrategyDetail> pageInfo = strategyDetailService.query(qo);
        Destination destination = new Destination();
        destination.setId(qo.getDestId());
        //pageInfo
        model.addAttribute("pageInfo",pageInfo);
        //tags
        model.addAttribute("tags",strategyTagService.selectBydestId(qo.getDestId()));
        List<Destination> toasts = destinationService.listToasts(qo.getDestId());
        model.addAttribute("toasts", toasts);
        model.addAttribute("dest", toasts.remove(toasts.size() - 1));
        return "strategy/list";
    }

    //http://localhost/strategy/commentAdd
    @RequestMapping("commentAdd")
    @ResponseBody
    @RequiredLogin
    public Object commentAdd(StrategyComment comment, @LoginUser UserInfo userInfo) {
        AjaxResult result = new AjaxResult();
        //设置用户信息
        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());
        comment.setLevel(userInfo.getLevel());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        //保存评论
        strategyCommentService.save(comment);

        //该攻略的评论数+1
        strategyStatsCacheService.incrNum(comment.getDetailId(),1,IStrategyStatsCacheService.STRATEGY_STATS_REPLYNUM);

        //查询该攻略的统计数
        StrategyStats vo = strategyStatsCacheService.getStrategyStats(comment.getDetailId());

        //飙升榜单加分
        strategyStatsCacheService.addScore(RedisKey.STRATEGY_STATS_UP_SORT,1,comment.getDetailId());
        return result.addData(vo.getReplynum());
    }

    //http://localhost/strategy/comment
    @RequestMapping("/comment")
    public String comment(@ModelAttribute("qo") StrategyCommentQueryObject qo, Model model) {
        //对象返回分页
        model.addAttribute("page", strategyCommentService.query(qo));
        return "strategy/commentTpl";
    }

    //http://localhost/strategy/commentThumbUp?toId=5da6e24b858c2532414d7d92&fromId=1
    @RequestMapping("/commentThumbUp")
    @ResponseBody
    @RequiredLogin
    public Object commentThumbUp(String toId, Long fromId) {
        strategyCommentService.commentThumbUp(toId, fromId);
        return new AjaxResult();
    }

    //http://localhost/strategy/favor?strategyId=2
    @RequestMapping("favor")
    @ResponseBody
    public Object favor(Long strategyId,@LoginUser UserInfo user){
        AjaxResult result = new AjaxResult();
        if (user == null){
            result.mark("请先登录");
            result.setCode(102);//在这个项目中约定的,表示没有登录的错误状态码
            return result;
        }

        boolean flag = strategyStatsCacheService.favor(strategyId, user.getId());

        //去Mysql数据库中保存/删除关系
        //System.err.println(user.getId());
        strategyDetailService.isFavor(user,strategyId);

        result.setSuccess(flag);

        //查询该攻略的统计数
        StrategyStats vo = strategyStatsCacheService.getStrategyStats(strategyId);

        //热门榜单加减分
        int num = flag ? 1: -1;
        strategyStatsCacheService.addScore(RedisKey.STRATEGY_STATS_HOT_SORT,num,strategyId);
        return result.addData(vo);

    }

    //http://localhost/strategy/strategyThumbup?strategyId=2
    @RequestMapping("strategyThumbup")
    @ResponseBody
    public Object strategyThumbup(Long strategyId,@LoginUser UserInfo user){
        AjaxResult result = new AjaxResult();
        if (user == null){
            result.mark("请先登录");
            result.setCode(102);//在这个项目中约定的,用来表示没有登录的错误状态码
            return result;
        }

        boolean flag = strategyStatsCacheService.strategyThumbup(strategyId, user.getId());
        result.setSuccess(flag);

        //查询该攻略的统计数
        StrategyStats vo = strategyStatsCacheService.getStrategyStats(strategyId);

        //热门榜单加分
        if (flag){
            strategyStatsCacheService.addScore(RedisKey.STRATEGY_STATS_HOT_SORT,1,strategyId);
        }
        return result.addData(vo);

    }

    ///strategy/share
    @RequestMapping("share")
    @ResponseBody
    public Object strategyShare(Long strategyId,@LoginUser UserInfo user){
        AjaxResult result = new AjaxResult();
        if (user == null){
            result.mark("请先登录");
            return result;
        }

        boolean flag = strategyStatsCacheService.strategyShare(strategyId, user.getId());
        result.setSuccess(flag);
        if (!flag) {
            result.setMsg("亲,今日已经分享过了");
        }
        //查询该攻略的统计数
        StrategyStats vo = strategyStatsCacheService.getStrategyStats(strategyId);



        return result.addData(vo);
    }

}
